<%@ page language="java" import="java.lang.*"  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
	String path = request.getContextPath();
%>
  <div class="widget-box" style="border:10px;margin:10px">
   <input type="hidden" id="instorage_inOrder_inPlanId" value="${inPlanId }">
	<!-- 表格div -->
	<div id="instorage_inOrder_grid-div-c" style="width:100%;margin:10px auto;">
		<!-- 	表格工具栏 -->
        <div id="instorage_inOrder_fixed_tool_div" class="fixed_tool_div detailToolBar">
              <label class="inline" for="instorage_inOrder_instorageHouseId" style="margin-right:20px;float: left">
				入库库区：
				<input id="instorage_inOrder_instorageHouseId" name="instorageHouseId">
			</label>
             <div id="instorage_inOrder___toolbar__-c" style="float:left;overflow:hidden;">
              
             </div>
        </div>
		<!-- 物料详情信息表格 -->
		<table id="instorage_inOrder_grid-table-c" style="width:100%;height:100%;"></table>
		<!-- 表格分页栏 -->
		<div id="instorage_inOrder_grid-pager-c"></div>
	</div>
</div>
<script type="text/javascript">
var context_path = '<%=path%>';
var inPlanId=$("#instorage_inOrder_inPlanId").val();
/* var cust=${sale.customer}; */
var oriDataDetail;
 var _grid_detail;        //表格对象
 var lastsel2;

//单元格编辑成功后，回调的函数
	var editFunction = function eidtSuccess(XHR){
		 var data = eval("("+XHR.responseText+")"); 
		if(data["msg"]!=""){
			layer.alert(data["msg"]);
		}
		jQuery("#instorage_inOrder_grid-table-c").jqGrid('setGridParam', 
				{
					postData: {
						id:$('#id').val(),
						queryJsonString:""
					} 
				}
		  ).trigger("reloadGrid");
	};
	
  
  	_grid_detail=jQuery("#instorage_inOrder_grid-table-c").jqGrid({
         url : context_path + '/instoragePlan/detailList?inPlanId='+inPlanId,
         datatype : "json",
         colNames : [ '详情主键','物料编号','物料名称','数量','可拆分数量','计划入库数量'],
         colModel : [ 
				{name : 'id',index : 'id',width : 20,hidden:true}, 
				{name : 'materialNo',index:'materialNo',width :20}, 
             {name : 'materialName',index:'materialName',width : 20}, 
             {name : 'amount',index:'amount',width : 20},
             {name : 'splitAmount',index:'splitAmount',width : 20},
             {name: 'planAmount', index: 'planAmount', width: 20,editable : true,editrules: {custom: true, custom_func: numberRegex},
               editoptions: {
                  size: 25,
                  dataEvents: [
                      {
                          type: 'blur',     
                          fn: function (e) {
                        	  var $element = e.currentTarget;
                        	  var $elementId = $element.id;
                        	  var rowid = $elementId.split("_")[0];
                        	  var id=$element.parentElement.parentElement.children[1].textContent;
                        	  var indocType = 1;
                        		  var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
                        		  if (!reg.test($("#"+$elementId).val())) {
                        			  layer.alert("非法的数量！(注：可以有两位小数的正实数)");
                        			  return;
                        		  }
                        	  $.ajax({
                        		  url:context_path + '/instoragePlan/updateSplitAmount',
                        		  type:"POST",
                        		  data:{id:id,planAmount:$("#"+rowid+"_planAmount").val()},
                        		  dataType:"json",
                        		  success:function(data){
                        		        if(!data.result){
                        		           layer.alert(data.msg);
                        		        }
                        		       reloadDetailTableList();
                        		      
                        		  }
                        	  }); 
                          }
                      }
                  ]
              }
             },
          ],
         rowNum : 20,
         rowList : [ 10, 20, 30 ],
         pager : '#instorage_inOrder_grid-pager-c',
         sortname : 'ID',
         sortorder : "asc",
         altRows: true,
         viewrecords : true,
         caption : "物料列表",
         autowidth:true,
         multiselect:true,
		 multiboxonly: true,
         loadComplete : function(data) 
         {
             var table = this;
             setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
             oriDataDetail = data;
         },
	   cellEdit: true,
	   cellsubmit : "clientArray",
  	   emptyrecords: "没有相关记录",
  	   loadtext: "加载中...",
  	   pgtext : "页码 {0} / {1}页",
  	   recordtext: "显示 {0} - {1}共{2}条数据",
    });
    //在分页工具栏中添加按钮
    $("#instorage_inOrder_grid-table-c").navGrid('#instorage_inOrder_grid-pager-c',{edit:false,add:false,del:false,search:false,refresh:false})
      .navButtonAdd('#instorage_inOrder_grid-pager-c',{  
  	   caption:"",   
  	   buttonicon:"ace-icon fa fa-refresh green",   
  	   onClickButton: function(){   
  	    reloadDetailTableList();
  	   }
  	});
  	
  	$(window).on('resize.jqGrid', function () {
  		$("#instorage_inOrder_grid-table-c").jqGrid( 'setGridWidth', $("#instorage_inOrder_grid-div-c").width() - 3 );
  		$("#instorage_inOrder_grid-table-c").jqGrid( 'setGridHeight', (document.documentElement.clientHeight - $("#instorage_inOrder_grid-pager-c").height() - 380) );
  	});
  	$(window).triggerHandler('resize.jqGrid');

  
//将数据格式化成两位小数：四舍五入
 function formatterNumToFixed(value,options,rowObj){
	if(value!=null){
		var floatNum = parseFloat(value);
		return floatNum.toFixed(2);
	}else{
		return "0.00";
	}
 } 
 //数量输入验证
function numberRegex(value, colname) {
    var regex = /^\d+\.?\d{0,2}$/;
    reloadDetailTableList();
    if (!regex.test(value)) 
        return [false, ""];
    else  return [true, ""];
}

  //工具栏
	  $("#instorage_inOrder___toolbar__-c").iToolBar({
	   	 id:"instorage_inOrder___tb__01",
	   	 items:[
	   	 	{label:"确认生成", onclick:outPlan}
	    ]
	  });
	function outPlan(){
	   var ids = jQuery("#instorage_inOrder_grid-table-c").jqGrid('getGridParam', 'selarrrow');
	   var checkedNum = getGridCheckedNum("#instorage_inOrder_grid-table-c","id");  //选中的数量
	   if($("#instorage_inOrder_instorageHouseId").val()==""){
	     layer.msg("请选择入库库区！",{time:1200,icon:2});
	     return;
	   }
	  if(checkedNum==0){
		layer.alert("请至少选择一个物料！");
	  }else{
	    $.ajax({
    	type : "POST",
    	url:context_path + "/instoragePlan/isHavePlanAmount?ids="+ids,
    	dataType : 'json',
    	cache : false,
    	success : function(data) {
	    	 if(data.result){ 
		  	    layer.confirm("确定选中的物料生成入库单？", function() {
	    		$.ajax({
	    			type : "POST",
	    			url:context_path + "/instoragePlan/inOrder?ids="+ids+"&houseId="+$("#instorage_inOrder_instorageHouseId").val(),
	    			dataType : 'json',
	    			cache : false,
	    			success : function(data) {
	    				if(data){
							layer.msg(data.msg, {icon: 1,time:1000});
	    				}else{
	    					layer.msg(data.msg, {icon: 2,time:1000});
	    				}
	    				reloadDetailTableList();  //重新加载表格
	    			}
	    		});
	    		
	    		});
	    	 }else{
	    	 	 layer.alert(data.msg);
	    	 }
    		}
    	});
	   }
	}
	function reloadDetailTableList(){
	  $("#instorage_inOrder_grid-table-c").jqGrid('setGridParam', 
				{
  	    			url:context_path + '/instoragePlan/detailList?inPlanId='+inPlanId,
					postData: {queryJsonString:""} //发送数据  :选中的节点
				}
		  ).trigger("reloadGrid");
	}
	 
$('#instorage_inOrder_fixed_tool_div .mySelect2').select2();

$("#instorage_inOrder_instorageHouseId").select2({
        placeholder: "请选择库区",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/area/getSelectArea",
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }

    });

  </script>
